package com.roc.service.impl.transReport;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.roc.newPage.IPageDao;
import com.roc.pojo.OperatorStatistics;
import com.roc.service.ServiceException;
import com.roc.service.transReport.IreportFormService;

/**    
*文件名称：              ReportFormServiceImpl.java  
*说明： 代理商交易报表
*
*@createTime 2017年8月15日 下午2:29:40  
*@author     zbl  
*@version    1.0 
**/
@Service
@Transactional
public class ReportFormServiceImpl implements IreportFormService {
	
	private static Logger  logger= Logger.getLogger(ReportFormServiceImpl.class);
	
	private final static String WX_PAY="微信扫码";  //微信  		1291反  1491正
	private final static String ZFB_PAY="支付宝扫码"; //支付宝 	1391反  1591正 
	private final static String YL_PAY="银联扫码"; //银联  		1191反  1691正
	private final static String T1_PAY="消费";  //t1		1011
	private final static String D0_PAY="实时收款";  //d0		1171

 
	@Autowired
	private IPageDao pageDao;
	
	@Override
	public List<Map<String, Object>> queryOperStatisticsById(String agentId,String minDate,String maxDate) throws ServiceException {
		List<Map<String, Object>> objList=null;
		try {
			if(null == agentId || null == minDate || null == maxDate){
				throw new ServiceException("获取表单信息异常！");
			}
			String resultDate=dateCompare(minDate, maxDate);
			if(null==resultDate){
				throw new ServiceException("请选择合理的日期范围！");
			}
			 
			String[] allDateArray=getDate(resultDate, minDate, maxDate);
			
			 
			String hql="from OperatorStatistics o where o.agentId=? and o.transDate>=? and o.transDate<=? ";
			Object[] paramObj={agentId,minDate,maxDate};
			List<?> operList=null;
			try {
				operList = pageDao.queryAll(hql, paramObj);
			} catch (Exception e) {
				throw new ServiceException("获取数据信息异常！");
			}
			if(null != operList && operList.size()>0){
				//处理结果集（Map<日期, 集合>）
				Map<String, List<OperatorStatistics>> resultMap= new HashMap<String, List<OperatorStatistics>>();
				for (Object object : operList) {
					
					OperatorStatistics os=(OperatorStatistics)object;
					
					List<OperatorStatistics> currentOp=null;
					if(resultMap.containsKey(os.getTransDate())){  //当前天数是否保存在map中
						currentOp=resultMap.get(os.getTransDate());
						currentOp.add(os);
					}else{
						currentOp=new ArrayList<OperatorStatistics>();
						currentOp.add(os);
						resultMap.put(os.getTransDate(), currentOp);
					}
				}
				 
				
				objList= new  ArrayList<Map<String, Object>>();
				Map<String, Object> payMap=null;
				for (int i = 0; i < 5; i++) {//五种类型  0/1/2/3/4
					payMap=new LinkedHashMap<String, Object>();
					 
					String[] payArray=new String[allDateArray.length];
					for (int j = 0; j < allDateArray.length; j++) { //天数(X)
						System.out.println(allDateArray[i]+"-----当前日期");
						List<OperatorStatistics> osList=resultMap.get(allDateArray[j]);
						
						if(null != osList && osList.size()>0){ //有交易
							payArray[j]=getAllAmtorAllNum(i, osList);
						}else{ //没交易
							payArray[j]=String.valueOf(0); //等于0
						}
						System.out.println(i+"-----"+payArray[j]);
					}
					String key="";
					switch (i) {
						case 0:
							key=WX_PAY;
							break;
						case 1:
							key=ZFB_PAY;
							break;
						case 2:
							key=YL_PAY;
							break;
						case 3:
							key=T1_PAY;
							break;
						default:
							key=D0_PAY;
							break;
					}
					payMap.put(key, payArray);
					objList.add(payMap);
				}
				payMap.put("xAixs", allDateArray); //x 轴 显示日期
				objList.add(payMap);
				return objList;
			}
		} catch (Exception e ) {
			logger.error("=====获取交易数据失败=====",e);
			throw new ServiceException(e.getMessage(),e);
		}
		return null;
	}
	
	
	/**
	 * 判断页面传来的日期是否在一个月内
	 * */
	private static String dateCompare(String minDate,String maxDate) throws Exception{
		SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMdd");
		try {
			Date mindate=sdf.parse(minDate);//开始日期
			Date maxdate=sdf.parse(maxDate);//结束日期
			Calendar c=Calendar.getInstance();
			c.setTime(mindate); 
			
			int minMonths=c.get(Calendar.MONTH)+1; //月份从0开始要加1
			int minYears=c.get(Calendar.YEAR);
			 
			c.setTime(maxdate); 
			int maxMonths=c.get(Calendar.MONTH)+1; //月份从0开始要加1
			int maxYears=c.get(Calendar.YEAR);
			System.out.println(minYears+"-"+minMonths+"|"+maxYears+"-"+maxMonths);
			if(minYears==maxYears &&  minMonths==maxMonths){
				if(minMonths<10){
					return String.valueOf(minYears)+"0"+minMonths;
				}else{
					return String.valueOf(minYears)+minMonths;
				}
				
			}
		} catch (ParseException e) {
			throw new Exception("请正确选择起始日期！");
		}
		return null;
	}
	
	/**
	 * 获取间隔的天数
	 * */
	private static String[] getDate(String sameYearMonth,String minDate,String maxDate) throws Exception{
		SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMdd");
		String[] newParam=null;
		try {
			
			Date mindate=sdf.parse(minDate);//开始日期
			Date maxdate=sdf.parse(maxDate);//结束日期
			Calendar c=Calendar.getInstance();
			c.setTime(mindate); 
			
			int minDay=c.get(Calendar.DAY_OF_MONTH);  
			 
			c.setTime(maxdate); 
			int maxDay=c.get(Calendar.DAY_OF_MONTH); 
			
			newParam=new String[maxDay-minDay+1];
			
			newParam[0]=String.valueOf(minDay);
			if(minDay<10){newParam[0]=sameYearMonth+"0"+newParam[0];}
			for (int i = 1; i <= maxDay-minDay; i++) {
				if(minDay+i<10){
					newParam[i]=sameYearMonth+"0"+String.valueOf(minDay+i);
				}else{
					newParam[i]=sameYearMonth+String.valueOf(minDay+i);
				}
			}
			 
		} catch (ParseException e) {
			throw new Exception("请正确选择起始日期！");
		}
		return newParam;
	}
	
	
	/**
	 * 根据支付类型获取该支付类型下总交易金额或总交易笔数
	 * @param type 详看switch
	 * @param operList  查询结果集
	 * */
	public String getAllAmtorAllNum(int type,  List<OperatorStatistics> operList){
		BigDecimal bd=new BigDecimal(0);
		for (OperatorStatistics os : operList) {
			String amt=os.getTransAmt(); 
			switch (type) {
				case 0: //微信扫码
					 if(os.getTransType().equals("1291") || os.getTransType().equals("1491")){
						 
						 bd=bd.add(new BigDecimal(amt));
					 }
					break;
				case 1://支付宝扫码
					 if(os.getTransType().equals("1391") || os.getTransType().equals("1591")){
						 bd=bd.add(new BigDecimal(amt));
					 }
					break;
				case 2://银联扫码
					 if(os.getTransType().equals("1191") || os.getTransType().equals("1691")){
						 bd=bd.add(new BigDecimal(amt));
					 }
					break;
				case 3: //t1 
					 if(os.getTransType().equals("1011") ){
						 bd=bd.add(new BigDecimal(amt));
					 }
					break;
				default://D0
					 if(os.getTransType().equals("1171") ){
						 bd=bd.add(new BigDecimal(amt));
					 }
					break;
			}
		}
		 
		return bd.toString();
	} 
	
	
	public static void main(String[] args) {
		try {
			//System.out.println(getDate("20170401", "20170814"));
			
			/*String resultDate=dateCompare("20170801", "20170816");
			System.out.println(resultDate);*/
			BigDecimal  bd= new BigDecimal(10);
			String a= bd.add(new BigDecimal(".08")).toString();
			 System.out.println(bd+"="+a);
		} catch (Exception e) {
			 e.printStackTrace();
		}
	}
}
